﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;

using ECCIT.IO;

namespace ECCIT.Report.Excel
{
    public class HtmlReport
    {
        private HtmlTemplate _template;
        private DataSet _dataSet;
        private IReportModel _reportModel;
        private HtmlTemplateRow _sampleRow;

        public HtmlReport(IReportModel reportModel, HtmlTemplate template, DataSet dataSet)
        {
            _reportModel = reportModel;
            _template = template;
            _dataSet = dataSet;

            if (_dataSet == null || _dataSet.Tables.Count == 0)
                throw new Exception("统计数据结果集不存在！");

            if (_reportModel == null)
                throw new Exception("统计模板信息不存在！");

            if (_template == null)
                throw new Exception("读取统计模板信息失败！");

            if (_template.Rows.Count > _reportModel.StartRowIndex)
                _sampleRow = _template.Rows[_reportModel.StartRowIndex.Value - 1].Clone();
        }

        public string GenerateStatisticsReport()
        {
            // remove blank rows in template
            RemoveBlankRowInTemplate();

            BindDataItems(_reportModel.Columns);

            //
            FillGenericCells(_reportModel.Columns.Where<IReportColumnModel>(col => col.Type>=2).ToList<IReportColumnModel>());

            return _template.ToString();
        }

        private void RemoveBlankRowInTemplate()
        {
            // remove blank rows in template
            int startRowIndex = _reportModel.StartRowIndex.Value;
            int remainRowCount = (_reportModel.HasFooter.HasValue && _reportModel.HasFooter.Value) ? startRowIndex + 1 : startRowIndex;

            int rowCount = _template.Rows.Count;
            while (rowCount > remainRowCount)
            {
                _template.Rows.RemoveAt(startRowIndex - 1);
                rowCount--;
            }
        }

        private bool IsBoldRow(DataRow dataRow)
        {
            if (dataRow.Table.Columns.Contains("CS") && dataRow["CS"] != null && dataRow["CS"] != DBNull.Value)
            {
                int order = -1;
                if (dataRow.Table.Columns["CS"].DataType == typeof(string))
                {
                    string sOrder = (string)dataRow["CS"];
                    int index = sOrder.LastIndexOf("_");
                    order = (index > -1) ? int.Parse(sOrder.Substring(index + 1)) : int.Parse(sOrder);
                }
                else if (dataRow.Table.Columns["CS"].DataType == typeof(int))
                {
                    order = (int)dataRow["CS"];
                }

                if (order % 100 == 0)
                    return true;
            }

            return false;
        }

        private void BindDataItems(IList<IReportColumnModel> columns)
        {
            if (columns == null) return;

            DataRowCollection dataRows = _dataSet.Tables[0].Rows;
            HtmlTemplateRow tr = null;
            bool boldFont = false;
            int dataRowIndex = 0;
            Hashtable sumTable = new Hashtable();
            //int sumRowIndex = _reportModel.StartRowIndex - 2;
            int i = 0;
            object fieldValue = null;
            string sFieldValue = string.Empty;
            foreach (DataRow dr in dataRows)
            {
                boldFont = IsBoldRow(dr);

                //tr = _template.Rows[_reportModel.StartRowIndex - 1].Clone();
                tr = _sampleRow.Clone();
                if (_reportModel.HasFooter.HasValue && _reportModel.HasFooter.Value)
                    _template.Rows.Insert(_template.Rows.Count - 2, tr);
                else
                    _template.Rows.Add(tr);

                HtmlTemplateCell currentCell = null;

                foreach (IReportColumnModel column in columns)
                {
                    fieldValue = null;
                    sFieldValue = string.Empty;

                    currentCell = tr.Cells[column.ColumnIndex.Value - 1];
                    if (currentCell == null) continue;

                    if (column.AutoNumber.HasValue && column.AutoNumber.Value)
                    {
                        if (!boldFont)
                            currentCell.InnerText = (dataRowIndex + 1).ToString();
                    }
                    else
                    {
                        fieldValue = dr[column.PhysicalName];
                        if (fieldValue != null && fieldValue != DBNull.Value)
                            sFieldValue = fieldValue.ToString();

                        if (column.Type == 2 || column.Type == -1)
                        {
                            if (sFieldValue == "") sFieldValue = "0";
                            if (_reportModel.MoneyUnit == "2" && column.Type == 2)
                                sFieldValue = Convert.ToString(Convert.ToDecimal(sFieldValue) / 10000);

                            if (sumTable.ContainsKey(column.ColumnIndex))
                                sumTable[column.ColumnIndex] = (decimal)sumTable[column.ColumnIndex] + Convert.ToDecimal(sFieldValue);
                            else
                                sumTable.Add(column.ColumnIndex, Convert.ToDecimal(sFieldValue));

                            //currentCell.InnerText = Utilities.FormatStatisticsMoney(sFieldValue);
                            currentCell.InnerText = sFieldValue;
                            //currentCell.align = "right";
                        }
                        else
                        {
                            currentCell.InnerText = sFieldValue;
                            if (column.Type == -2)
                            {
                                if (i > 0)
                                {
                                    if (dataRows[i - 1][column.PhysicalName].ToString() == sFieldValue)
                                        currentCell.InnerText = "";
                                }
                            }
                        }
                    }

                    if (currentCell != null)
                    {
                        //currentCell.style.fontFamily = "Arial";
                        //currentCell.style.fontSize = "9pt";
                        //currentCell.innerHTML = "<nobr>" + currentCell.innerHTML + "</nobr>";
                        //if (boldFont)
                        //    currentCell.innerHTML = "<b>" + currentCell.innerHTML + "</b>";
                        currentCell.InnerText = "<nobr>" + currentCell.InnerText + "</nobr>";
                        if (boldFont)
                            currentCell.InnerText = "<b>" + currentCell.InnerText + "</b>";
                    }
                }

                i++;
                if (!boldFont) dataRowIndex++;
            }
        }

        private IReportColumnModel FindColumnByIndex(IList columns, int columnIndex)
        {
            foreach (IReportColumnModel column in columns)
            {
                if (column.ColumnIndex == columnIndex)
                    return column;
            }

            return null;
        }

        private void FillGenericCells(IList<IReportColumnModel> columns)
        {
            if (columns == null) return;

            //foreach (IReportColumnModel column in columns)
            //{
            //    switch (column.Type)
            //    {
            //        case 3:       //统计开始日期
            //            FillStartDateCell(column);
            //            break;
            //        case 4:       //统计结束日期
            //            //alert(StatisticsMain.GetEndDate("yyyy年mm月dd日").value);
            //            FillEndDateCell(column);
            //            break;
            //        case 5:       //打印日期
            //            FillPrintDateCell(column);
            //            break;
            //        case 6:       //单位信息
            //            FillUnitCell(column);
            //            break;
            //        case 7:
            //            FillProjectCell(column);
            //            break;
            //        default:
            //            break;
            //    }
            //}
        }
    }
}
